package com.luomo.java.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * 解决CAS ABA问题
 *
 * @author LiuMei
 * @date 2021-01-14.
 */
public class ABADemo {

    static AtomicReference<Integer> atomicReference = new AtomicReference<>(100);
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            atomicReference.compareAndSet(100, 101);
            atomicReference.compareAndSet(101, 100);
        }, "t1").start();
        new Thread(() -> {
            try {
                //确保t1线程完成ABA操作
                TimeUnit.SECONDS.sleep(1);
                System.out.println(atomicReference.compareAndSet(100, 2021) + "\t" + atomicReference.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("============解决ABA============");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t 第1次版本号：" + stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
                atomicStampedReference.compareAndSet(100, 101, stamp, stamp + 1);
                stamp = atomicStampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + "\t 第2次版本号：" + stamp);
                atomicStampedReference.compareAndSet(101, 100, stamp, stamp + 1);
                stamp = atomicStampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + "\t 第3次版本号：" + stamp);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t3").start();
        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t 第1次版本号：" + stamp);
            try {
                TimeUnit.SECONDS.sleep(3);
                boolean result = atomicStampedReference.compareAndSet(100, 2021, stamp, stamp + 1);
                stamp = atomicStampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + "\t result：" + result + "\t当前版本号：" + stamp);
                System.out.println("最新值："+atomicStampedReference.getReference());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t4").start();
    }

}
